package route

import (
	"net/http"
	"pdocker/docker"
	. "pdocker/tool/docker"
	"strings"

	docker_types "github.com/docker/docker/api/types"
	"github.com/gin-gonic/gin"
)

// @Summary 获取容器状态
// @Tags docker
// @Description "查询容器"
// @Produce json
// @Success 200 {object} docker.Image
// @Router /docker/container/list [get]
func ShowUserContainers(c *gin.Context) {
	containers, err := Cli.ContainerList(Ctx, docker_types.ContainerListOptions{
		All: false,
	})
	if err != nil {
		simpleReturn(c, http.StatusBadRequest, "", "格式错误")
	} else {
		for _, container := range containers {
			_, ok := container.NetworkSettings.Networks["sebafi-pro_sebafi"]
			if !strings.Contains(container.Image, "harbor") && !ok {
				c.String(http.StatusOK, "%s %s\n", container.Names[0][1:], container.Image)
				for key, ns := range container.NetworkSettings.Networks {
					c.String(http.StatusOK, "\t%s -> %s %s %s \n", key, ns.IPAddress, ns.Gateway, ns.NetworkID)
				}

				for _, port := range container.Ports {
					c.String(http.StatusOK, "\t\t%d --> %d\n", port.PublicPort, port.PrivatePort)
				}
			}
		}
	}

}

// @Summary 获取容器标签
// @Tags docker
// @Description "查询容器标签"
// @Produce json
// @Success 200 {string} string
// @Router /docker/container/label [get]
func ShowContainerLabel(c *gin.Context) {
	containers, _ := Cli.ContainerList(Ctx, docker_types.ContainerListOptions{
		All: false,
	})
	for _, container := range containers {
		c.String(http.StatusOK, "%s %s\n", container.Image, container.Names[0][1:])
		for k, v := range container.Labels {
			c.String(http.StatusOK, "\t%s -> %s \n", k, v)
		}

	}
}

func GetContainerLocalIp(c *gin.Context) {
	container, err := docker.GetContainerByName(c.Param("name"))
	if err != nil {
		simpleReturn(c, http.StatusBadRequest, "", "格式错误")
	} else {
		c.JSON(http.StatusOK, gin.H{
			"container": c.Param("name"),
			"ip":        docker.GetContainerIP(container),
			"image":     container.Image,
		})
	}
}
